import router from "@/router";
import { userLoginUserStore } from "@/store/userStore";
import ACCESS_ENUM from "@/access/accessEnum";
import checkAccess from "@/access/checkAccess";
import { getLoginUserUsingGet } from "@/api/userController";

router.beforeEach(async (to, from, next) => {
  // 判断是否需要登录
  const loginUserStore = userLoginUserStore();
  let loginUser = loginUserStore.loginUser;
  // 如果之前没有尝试登录过，自动登录
  if (!loginUser || !loginUser.userRole) {
    // 保证同步的状态
    await loginUserStore.fetchUserLogin();
    loginUser = loginUserStore.loginUser;
  }

  //   获取当前页面登录权限
  const needAccess = (to.meta?.access as string) ?? ACCESS_ENUM.NO_LOGIN;
  if (needAccess !== ACCESS_ENUM.NO_LOGIN) {
    //   没有登录, 跳转到登录页面
    if (
      !loginUser ||
      !loginUser.userRole ||
      loginUser.userRole === ACCESS_ENUM.NO_LOGIN
    ) {
      next(`/user/login?redirect=${to.fullPath}`);
    }
    //   如果已经登录, 判断权限
    if (!checkAccess(loginUser, needAccess)) {
      next("/noAuth");
      return;
    }
  }
  next();
});
